package com.dyw.blog.handler;

import com.alibaba.fastjson.JSON;
import com.dyw.blog.dao.entity.SysUser;
import com.dyw.blog.service.SysUserService;
import com.dyw.blog.utils.UserThreadLocal;
import com.dyw.blog.vo.ErrorCode;
import com.dyw.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Devil
 * @create 2022-02-11 17:10
 */
@Component
@Slf4j
@SuppressWarnings("all")
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private SysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在执行controller方法(handler)之前进行执行
        /**
         * 1. 需要判断 请求接口路径 是否为HanlderMethod(Controller方法)
         * 2. 判断token是否为空, 如果为空 未登录
         * 3. 如果token不为空 登陆验证loginservice checktoken
         * 4. 如果认证成功 放行即可
         */
        if(!(handler instanceof HandlerMethod)){
            //handler 可能是RequsetResulrceHanlder Springboot程序 访问静态资源
            // 默认去classpath 下的static目录去查询
            return true;
        }

        String token = request.getHeader("Authorization");

        //打印日志
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if(StringUtils.isBlank(token)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSON(Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg())));
            return false;
        }
        SysUser sysUser = sysUserService.checkToken(token);
        if(sysUser==null){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSON(Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg())));
            return false;
        }

        //将用户信息存放进ThreadLocal中 方便Controller获取\
        UserThreadLocal.put(sysUser);
        //到此位置验证结束 验证成功 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //使用UserThreadLocal中的数据后 需要清除信息 否则会造成内存泄露
        UserThreadLocal.remove();

    }
}
